<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2021/3/1
 * Time: 14:03
 */
namespace App\Api\Controllers\CustomerApplets;

use App\Api\Controllers\CustomerApplets\BaseController as BBaseController;
use App\Models\MerchantStoreAppidSecret;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ImmediateDeliveryController extends BBaseController
{

    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）
     *
     * @param $store_id
     * @return mixed|string
     */
    function get_access_token($store_id)
    {
        $merchant_store_appid_secrets_obj = MerchantStoreAppidSecret::where('store_id', $store_id);
        if (!isset($merchant_store_appid_secrets_obj->wechat_appid) || !isset($merchant_store_appid_secrets_obj->wechat_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '微信小程序参数未配置'
            ]);
        }

        $appid = $merchant_store_appid_secrets_obj->wechat_appid;
        $secret = $merchant_store_appid_secrets_obj->wechat_secret;

        if (Cache::has($appid)) {
            $access_token = Cache::get($appid);
        } else {
            $access_token = '';
            if ($merchant_store_appid_secrets_obj->wechat_access_token_invalid_date && (strtotime($merchant_store_appid_secrets_obj->wechat_access_token_invalid_date) > time())) {
                $access_token = $merchant_store_appid_secrets_obj->wechat_access_token;
            }

            if (!$access_token) {
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
                $res = $this->https_request($url, '', 'get', 'json');
                Log::info('获取微信小程序access_token');
                Log::info($res);
                $access_token = $res['access_token'];
                $merchantStoreAppIdSecretModel = new MerchantStoreAppidSecret();
                $merchantStoreAppIdSecretModel->updateWeChatInfo($appid, $res);
                Cache::put($appid, $access_token, 100);
            }
        }

        return $access_token;
    }


    /**
     * curl请求
     *
     * @param $url
     * @param string $data
     * @param string $type
     * @param string $res
     * @return mixed
     */
    function https_request($url, $data = '', $type = 'get', $res = 'json')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post'){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, 320));
        }
        $output = curl_exec($curl);
        curl_close($curl);
        if ($res == 'json') {
            return json_decode($output, true);
        }
    }


    /**
     * 第三方代商户发起开通即时配送权限
     *
     * 查询即时配送接口已支持的配送公司和delivery_id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function businessOpen(Request $request)
    {
        $store_id = $request->post('store_id', ''); //系统门店id

        try {
            $access_token = $this->get_access_token($store_id);
            $requestUrl = "https://api.weixin.qq.com/cgi-bin/express/local/business/open?access_token=".$access_token;
            $requestResultObj = $this->curl_post_https($requestUrl);
            $requestResult = json_decode($requestResultObj, true);
            if ($requestResult['errcode'] == 0 || !isset($requestResult['errcode'])) {
                if ($requestResult['resultcode'] == 0) {
                    return $this->responseDataJson(1, $requestResult['resultmsg']);
                } else {
                    return $this->responseDataJson(2, $requestResult['resultmsg']);
                }
            } else {
                return $this->responseDataJson(2, $requestResult['errmsg']);
            }
        } catch (\Exception $e) {
            Log::info('第三方代商户发起开通即时配送权限-error');
            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
            return $this->responseDataJson(-1);
        }
    }









    /**
     * 获取已支持的配送公司列表
     *
     * 查询即时配送接口已支持的配送公司和delivery_id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
//    public function businessDeliveryGetAll(Request $request)
//    {
//        $store_id = $request->post('store_id', ''); //
//        $ = $request->post('', ''); //
//        $ = $request->post('', ''); //
//
//        try {
//            //
//            $access_token = $this->get_access_token($store_id);
//            $requestUrl = "https://api.weixin.qq.com/cgi-bin/express/local/business/delivery/getall?access_token=".$access_token;
//            $requestResultObj = $this->curl_post_https($requestUrl);
//            $requestResult = json_decode($requestResultObj, true);
//            if ($requestResult['errcode'] == 0 || !isset($requestResult['errcode'])) {
//                if ($requestResult['resultcode'] == 0) {
//                    if (isset($requestResult['list']) && !empty($requestResult['list'])) {
//                        $is_cache = Cache::has('business_delivery_getall');
//                        if ($is_cache) {
//                            $data = Cache::get('business_delivery_getall');
//                        } else {
//                            $data = $requestResult['list'];
//                            Cache::put('business_delivery_getall', $data, 10000);
//                        }
//                    } else {
//                        $data = [];
//                    }
//                    return $this->responseDataJson(1, $requestResult['resultmsg'], $data);
//                } else {
//                    return $this->responseDataJson(2, $requestResult['resultmsg']);
//                }
//            } else {
//                return $this->responseDataJson(2, $requestResult['errmsg']);
//            }
//        } catch (\Exception $e) {
//            Log::info('获取已支持的配送公司列表-error');
//            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
//            return $this->responseDataJson(-1);
//        }
//    }


    /**
     * 下配送单
     *
     * 商家可调用本接口向配送公司请求下配送单，配送公司会返回这一单的配送单号、配送费、预计骑手接单时间等信息。如遇下单错误，请先确认一下编码方式，python建议 json.dumps(b, ensure_ascii=False)，php建议 json_encode($arr, JSON_UNESCAPED_UNICODE) 可预约时间：达达：72小时内，闪送2小时以后，48小时以内
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
//    public function businessOrderAdd(Request $request)
//    {
//        try {
//            //使用授权码获取授权信息
//            $authorizationCodeResult = $this->getAuthorizerAccessToken($config['app_id'], $message['AuthorizationCode']);
//            if($authorizationCodeResult['status'] == 200) {
//                $access_token = $authorizationCodeResult['data']['authorization_info']['authorizer_access_token'];
//
//                //更新该授权方 appid的authorizer_refresh_token
//                $authorizer_refresh_token = DB::table('customerapplets_authorize_appids')
//                    ->where([
//                        't_appid' => $message['AppId'],
//                        'AuthorizerAppid' => $message['AuthorizerAppid']
//                    ])
//                    ->update([
//                        'authorizer_refresh_token' =>$authorizationCodeResult['data']['authorization_info']['authorizer_refresh_token'],
//                        'updated_at' => date("Y-m-d H:i:s",time())
//                    ]);
//            }
//
//            $requestDomainUrl = "https://api.weixin.qq.com/cgi-bin/express/local/business/order/add?access_token=".$access_token;
//            $requestDataArr = [
//                "cargo"=>[ //是,货物信息
//                    "cargo_first_class"=> "美食夜宵", //string,是,品类一级类目
//                    "cargo_second_class" => "零食小吃", //string	,是,品类二级类目
//                    "goods_detail" => [ //否,货物详情,最长不超过10240个字符
//                        "goods" => [ //是,货物列表
//                            [
//                                "good_count" => 1, //number,是,货物数量
//                                "good_name" => "水果", //string,是,货品名称
//                                "good_price" => 10, //number,否,货品单价,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数)
//                                "good_unit" => "元" //string	,否,货品单位,最长不超过20个字符
//                            ],
//                            [
//                                "good_count" => 2,
//                                "good_name" => "蔬菜",
//                                "good_price" => 20,
//                                "good_unit" => "元"
//                            ]
//                        ]
//                    ],
//                    "goods_height" => 1, //number,否,货物高度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为(0-45]
//                    "goods_length" => 3, //number,否,货物长度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为(0-65]
//                    "goods_value" => 5, //number,是,货物价格,单位为元,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为(0-5000]
//                    "goods_weight" => 1, //number,是,货物重量,单位为kg,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为(0-50]
//                    "goods_width" => 2, //number,否,货物宽度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为(0-50]
//                    "goods_pickup_info" => $goods_pickup_info, //string,否,货物取货信息,用于骑手到店取货,最长不超过100个字符
//                    "goods_delivery_info" => $goods_delivery_info, //string,否,货物交付信息,最长不超过100个字符
//                ],
//                "delivery_id" => "SFTC", //string,是,配送公司ID
//                "delivery_sign" => "01234567890123456789", //string,是,用配送公司提供的appSecret加密的校验串
//                "openid" => "oABC123456", //string,是,下单用户的openid
//                "order_info" => [ //是,订单信息
//                    "delivery_service_code" => "", //string,否,配送服务代码:不同配送公司自定义,顺丰和达达不填
//                    "expected_delivery_time" => 0, //number,0,否,期望派单时间(达达支持,表示达达系统调度时间,到那个时间才会有状态更新的回调通知),unix-timestamp,比如1586342180
//                    "expected_finish_time" => $expected_finish_time, //number,0,否,期望送达时间(美团、顺丰同城急送支持),unix-timestamp,比如1586342180
//                    "expected_pick_time" => $expected_pick_time, //number,0,否,期望取件时间(闪送、顺丰同城急送支持,闪送需要设置两个小时后的时间,顺丰同城急送只需传expected_finish_time或expected_pick_time其中之一即可,同时都传则以expected_finish_time为准),unix-timestamp,比如1586342180
//                    "is_direct_delivery" => 0, //number,否,是否选择直拿直送(0-不需要;1-需要.选择直拿直送后,同一时间骑手只能配送此订单至完成,配送费用也相应高一些,闪送必须选1,达达可选0或1,其余配送公司不支持直拿直送)
//                    "cash_on_delivery" => $cash_on_delivery, //number,否,骑手应付金额,单位为元,精确到分
//                    "cash_on_pickup" => $cash_on_pickup, //number,否,骑手应收金额,单位为元,精确到分
//                    "rider_pick_method" => $rider_pick_method, //number,否,物流流向:1-从门店取件送至用户;2-从用户取件送至门店
//                    "is_finish_code_needed" => 1, //number,否,收货码(0-不需要;1-需要.收货码的作用是:骑手必须输入收货码才能完成订单妥投)
//                    "is_insured" => 0, //number,0,否,是否保价:0-非保价;1-保价
//                    "declared_value" => $declared_value, //number,否,保价金额,单位为元,精确到分
//                    "is_pickup_code_needed" => 1, //number,否,取货码(0-不需要;1-需要.取货码的作用是:骑手必须输入取货码才能从商家取货)
//                    "note" => "test_note", //string,否,备注,最长不超过200个字符
//                    "order_time" => 1555220757, //number,否,用户下单付款时间,顺丰必填,比如1555220757
//                    "order_type" => 0, //number,0,否,订单类型:0-即时单;1-预约单,如预约单,需要设置expected_delivery_time或expected_finish_time或expected_pick_time
//                    "poi_seq" => "1111", //string,否,门店订单流水号,建议提供,方便骑手门店取货,最长不超过32个字符
//                    "tips" => 0 //number,否,小费,单位为元,下单一般不加小费
//                ],
//                "receiver" => [ //是	,收件人信息
//                    "address" => "xxx地铁站", //string,是,地址(街道、小区、大厦等,用于定位)
//                    "address_detail" => "2号楼202", //string,是,地址详情(楼号、单元号、层号)
//                    "city" => "北京市", //string	,是,城市名称:如广州市
//                    "coordinate_type" => 0, //number,0,否,坐标类型:0-火星坐标(高德,腾讯地图均采用火星坐标);1-百度坐标
//                    "lat" => 40.1529600000, //number,是,纬度(火星坐标或百度坐标,和coordinate_type字段配合使用,精确到小数点后6位)
//                    "lng" => 116.5060300000, //number,是,经度(火星坐标或百度坐标,和coordinate_type字段配合使用,确到小数点后6位)
//                    "name" => "老王", //string,是,姓名,最长不超过256个字符
//                    "phone" => "18512345678" //string,是,电话/手机号,最长不超过64个字符
//                ],
//                "sender" => [ //是,发件人信息,顺丰同城急送必须填写,美团配送、达达、闪送,若传了shop_no的值可不填该字段
//                    "address" => "xx大厦", //string,是,地址(街道、小区、大厦等,用于定位)
//                    "address_detail" => "1号楼101", //string	,是,	地址详情(楼号、单元号、层号)
//                    "city" => "北京市", //string,是,城市名称:如广州市
//                    "coordinate_type" => 0, //number,0,否,坐标类型.0-火星坐标(高德,腾讯地图均采用火星坐标),1-百度坐标
//                    "lat" => 40.4486120000, //number,是,	纬度(火星坐标或百度坐标,和coordinate_type字段配合使用,精确到小数点后6位)
//                    "lng" => 116.3830750000, //number,是,经度(火星坐标或百度坐标,和coordinate_type字段配合使用,确到小数点后6位)
//                    "name" => "刘一", //string,是,姓名,最长不超过256个字符
//                    "phone" => "13712345678" //string,是,电话/手机号,最长不超过64个字符
//                ],
//                "shop" => [ //是	商品信息,会展示到物流通知消息中
//                    "goods_count" => 2, //number,是,商品数量
//                    "goods_name" => "宝贝", //string	,是,商品名称
//                    "img_url" => "https =>//mmbiz.qpic.cn/mmbiz_png/xxxxxxxxx/0?wx_fmt=png", //string,是,商品缩略图url
//                    "wxa_path" => "/page/index/index", //string,是,商家小程序的路径,建议为订单页面
//                    "wxa_appid" => $wxa_appid //string,否,若结算方式为:第三方向配送公司统一结算,商户后续和第三方结算,则该参数必填;在该结算模式下,第三方用自己的开发小程序替授权商户发起下单,并将授权小程序的appid给平台,后续配送通知中可回流授权商户小程序
//                ],
//                "shop_no" => "12345678", //string,是,商家门店编号,在配送公司登记,如果只有一个门店,美团闪送必填,值为店铺id
//                "sub_biz_id" => "sub_biz_id_1", //string,否,子商户id,区分小程序内部多个子商户
//                "shop_order_id" => "SFTC_001", //string,是,唯一标识订单的ID,由商户生成,不超过128字节
//                "shopid" => "122222222", //string,是,商家id,由配送公司分配的appkey
//                "delivery_token" => "xxxxxxxx" //string,否,预下单接口返回的参数,配送公司可保证在一段时间内运费不变
//            ];
//            $requestData = json_encode($requestDataArr, JSON_UNESCAPED_UNICODE);
//            $requestDomainResult = $this->curl_post_https($requestDomainUrl, $requestData);
//
//        } catch (\Exception $e) {
//            Log::info('下配送单-error');
//            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
//            return $this->responseDataJson(-1);
//        }
//    }



}
